package cn.fscode.code.generator.controller;

import cn.fscode.code.generator.model.po.TemplateGroupPO;
import cn.fscode.code.generator.model.req.TemplateGroupListReq;
import cn.fscode.code.generator.model.resp.TemplateGroupResp;
import cn.fscode.code.generator.service.TemplateGroupService;
import cn.fscode.commons.core.response.Resp;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author shenguangyang
 */
@RestController
@RequestMapping("/api/templateGroup")
@RequiredArgsConstructor
public class TemplateGroupController {
    private final TemplateGroupService templateGroupService;

    /**
     * 查询所有记录
     *
     * @return 返回集合，没有返回空List
     */
    @GetMapping("list")
    public Resp<List<TemplateGroupResp>> listTemplateGroup(TemplateGroupListReq req) {
        return Resp.ok(templateGroupService.listTemplateGroup(req));
    }

    /**
     * 根据主键查询
     *
     * @param id 主键
     * @return 返回记录，没有返回null
     */
    @GetMapping("getById")
    public Resp<TemplateGroupPO> get(@RequestParam("id") Long id) {
        TemplateGroupPO group = templateGroupService.getById(id);
        return Resp.ok(group);
    }

    /**
     * 新增，忽略null字段
     *
     * @param templateGroupPO 新增的记录
     * @return 返回影响行数
     */
    @PostMapping("save")
    public Resp<TemplateGroupPO> save(@RequestBody TemplateGroupPO templateGroupPO) {
        templateGroupService.save(templateGroupPO);
        return Resp.ok(templateGroupPO);
    }

    /**
     * 修改，忽略null字段
     *
     * @param templateGroupPO 修改的记录
     * @return 返回影响行数
     */
    @PostMapping("update")
    public Resp<Object> update(@RequestBody TemplateGroupPO templateGroupPO) {
        TemplateGroupPO group = templateGroupService.getByName(templateGroupPO.getGroupName());
        if (group != null && !Objects.equals(group.getId(), templateGroupPO.getId())) {
            throw new RuntimeException(templateGroupPO.getGroupName() + " 已存在");
        }
        templateGroupService.updateById(templateGroupPO);
        return Resp.ok();
    }

    /**
     * 删除记录
     *
     * @param templateGroupPO 待删除的记录
     * @return 返回影响行数
     */
    @DeleteMapping("delete")
    public Resp<Object> delete(@RequestBody TemplateGroupPO templateGroupPO) {
        templateGroupService.deleteGroup(templateGroupPO);
        return Resp.ok();
    }

    /**
     * 删除记录
     *
     * @param ids 待删除的记录
     * @return 返回影响行数
     */
    @DeleteMapping("deleteBatch")
    public Resp<Object> deleteBatch(@RequestParam("ids") Long[] ids) {
        templateGroupService.deleteGroupBatch(Arrays.asList(ids));
        return Resp.ok();
    }
}